package com.saver.modules.sys.oauth2;

import com.saver.common.exception.UnExitUserException;
import com.saver.modules.sys.dao.SysParamDao;
import com.saver.modules.sys.dao.SysUserDao;
import com.saver.modules.sys.dao.SysUserTokenDao;
import com.saver.modules.sys.entity.SysParamEntity;
import com.saver.modules.sys.entity.SysUserEntity;
import com.saver.modules.sys.entity.SysUserTokenEntity;
import com.saver.modules.sys.service.SysRoleService;
import com.saver.modules.sys.service.SysUserTokenService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 身份权限源
 *
 * @author yuxiaolong
 * @email 1005471232@qq.com
 * @date 2018年08月30日 下午10:38
 */
@Component
public class OAuth2Realm extends AuthorizingRealm {

    @Autowired
    private SysUserDao sysUserDao;

    private final static String TOKEN_EXPIRE_TIME = "TOKEN_EXPIRE_TIME";

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserTokenDao sysUserTokenDao;

    @Autowired
    private SysParamDao sysParamDao;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof OAuth2Token;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SysUserEntity user = (SysUserEntity) principals.getPrimaryPrincipal();

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(user.getAccess());
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String accessToken = (String) token.getPrincipal();

        //根据accessToken，查询用户信息
        SysUserTokenEntity tokenEntity = sysUserTokenDao.findByToken(accessToken);
        //token失效
        if (tokenEntity == null || tokenEntity.getExpireTime().getTime() < System.currentTimeMillis()) {
            throw new IncorrectCredentialsException("token失效，请重新登录");
        }

        //查询用户信息
        Optional<SysUserEntity> byId = sysUserDao.findById(tokenEntity.getUserId());
        if (byId.isPresent()) {
            SysUserEntity sysUserEntity = byId.get();
            //账号锁定
            if (sysUserEntity.getStatus() == 0) {
                throw new LockedAccountException("账号已被锁定,请联系管理员");
            }

            List<Map<String, Object>> list = sysRoleService.queryRoleList(sysUserEntity.getUserId());
            sysUserEntity.setPassword(null);
            sysUserEntity.setSalt(null);
            Set<String> set = new HashSet<>();
            Set<Long> roleIds = new HashSet<>();

            for (int i = 0; i < list.size(); i++) {
                Integer roleId = (Integer) list.get(i).get("roleId");
                roleIds.add(roleId.longValue());
                set.add((String) list.get(i).get("roleName"));
            }
            sysUserEntity.setAccess(set);
            sysUserEntity.setRoleIds(roleIds);
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(sysUserEntity, accessToken, getName());
            return info;
        } else {
            throw new UnExitUserException("用户已不存在");
        }
    }
}
